[Home] Python으로 돌아가기

Matplotlib-3 (5) 3D 그래프(Axes3D)

(5) 3D 그래프

1) line and scatter


import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # 3D plot을 위해 필요
import numpy as np

# line plot
fig = plt.figure()
ax = fig.gca(projection='3d') # Axes3D 객체 생성

theta = np.linspace(-4*np.pi,4*np.pi,100)
z = np.linspace(-2,2,100)

r = z**2+1
x = r*np.sin(theta)
y = r*np.cos(theta)

ax.plot(x,y,z,label='parametric curve')
ax.scatter(x,y,z)
ax.legend()
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

fig.tight_layout()
plt.show()
    
3D line and scatter plot

2) surface

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d') # Axes3D 객체 생성

X=np.arange(-5,5,0.25)
Y=np.arange(-5,5,0.25)
X,Y = np.meshgrid(X,Y) # 격자 grid 생성
R = np.sqrt(X**2+Y**2)
Z = np.sin(R)

surf = ax.plot_surface(X,Y,Z,cmap='coolwarm',lw=0,antialiased=False)
wire = ax.plot_wireframe(X,Y,Z,color='r',lw=0.1)
fig.colorbar(surf,shrink=0.5,aspect=5)
fig.tight_layout()
plt.show()
3D surface plot

3) bar3d

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# setup the figure and axes
fig = plt.figure(figsize=(8, 3))
ax1 = fig.add_subplot(121, projection='3d') # Axes3D 객체 생성
ax2 = fig.add_subplot(122, projection='3d')

# fake data
_x = np.arange(4)
_y = np.arange(5)
_xx, _yy = np.meshgrid(_x, _y) # 격자 grid 생성
x, y = _xx.ravel(), _yy.ravel() # 다차원 배열을 1차원 배열로 풀기

top = x + y
bottom = np.zeros_like(top) # top과 같은 사이즈의 0 배열 생성
width = depth = 1

ax1.bar3d(x, y, bottom, width, depth, top, shade=True)
ax1.set_title('Shaded')

ax2.bar3d(x, y, bottom, width, depth, top, shade=False)
ax2.set_title('Not Shaded')

plt.show()
3D bar plot